package com.morningstar.system.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.morningstar.system.dao.entity.SysFileBiz;
import com.morningstar.system.dao.mapper.SysFileBizMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件业务关系服务类
 */
@Slf4j
@Service
public class SysFileBizService extends ServiceImpl<SysFileBizMapper, SysFileBiz> {

    @Transactional(rollbackFor = Exception.class)
    public void saveFileBiz(Long fileId, Long bizId, String bizType, String bizName) {
        baseMapper.delete(
                new LambdaQueryWrapper<SysFileBiz>()
                        .eq(SysFileBiz::getBizId, bizId)
                        .eq(SysFileBiz::getBizType, bizType)
        );
        SysFileBiz sysFileBiz = new SysFileBiz();
        sysFileBiz.setFileId(fileId);
        sysFileBiz.setBizId(bizId);
        sysFileBiz.setBizType(bizType);
        sysFileBiz.setBizName(bizName);
        baseMapper.insert(sysFileBiz);
    }

    public Map<Long, List<String>> selectFileBizMap(List<Long> fileIdList) {
        if (CollUtil.isEmpty(fileIdList)) {
            return new HashMap<>();
        }
        LambdaQueryWrapper<SysFileBiz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysFileBiz::getFileId, fileIdList);
        List<SysFileBiz> sysFileBizList = this.list(queryWrapper);
        if (CollUtil.isEmpty(sysFileBizList)) {
            return new HashMap<>();
        }
        return sysFileBizList.stream().collect(HashMap::new, (m, v) -> {
            m.computeIfAbsent(v.getFileId(), k -> CollUtil.newArrayList()).add(v.getBizName());
        }, HashMap::putAll);
    }

    public List<String> selectBizNameList(Long fileId) {
        LambdaQueryWrapper<SysFileBiz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysFileBiz::getFileId, fileId);
        return this.list(queryWrapper).stream().map(SysFileBiz::getBizName).toList();
    }
}
